package com.jlnk.stockdemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.activity.NewsActivity;
import com.jlnk.stockdemo.bean.NewsResponse;
import com.jlnk.stockdemo.viewmodel.NewsViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import java.util.ArrayList;
import java.util.List;

public class NewsFragment extends Fragment {
    private static final String TAG = "NewsFragment";
    private NewsViewModel newsViewModel;
    private ListView lv_news;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        lv_news = view.findViewById(R.id.lv_news);
        lv_news.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), NewsActivity.class);
                NewsResponse.Data.News news = newsViewModel.getNewsLiveData().getValue().get(position);
                intent.putExtra("title", news.getTitle());
                intent.putExtra("datetime", news.getDateTime());
                intent.putExtra("content", news.getContent());
                startActivity(intent);
            }
        });
        newsViewModel = new ViewModelProvider(this).get(NewsViewModel.class);
        newsViewModel.getNewsLiveData().observe(getViewLifecycleOwner(), newsItems -> {
            // 更新UI
            List<String> contentList = new ArrayList<>();
            for (NewsResponse.Data.News news : newsItems) {
                contentList.add(news.getContent());
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.item_news, contentList);
            lv_news.setAdapter(adapter);
        });
        newsViewModel.fetchNews();
    }

}
